<template>

  <div class="min-wrap">
    <div class="body-wrap">
      <div class="head">
        <span :class="{active:loginType==='phone'}"
          @click="loginType='phone'">验证码登录</span>
        <span :class="{active:loginType==='pwd'}"
          @click="loginType='pwd'">密码登录</span>
      </div>
      <div>
        <div>
          <PhoneForm v-model="form"
            ref="form"
            :type="loginType==='phone'?'':'pwd-login'"
            :layout="phoneFormLayout"
            :errMsgOffset="139"
            @handleEnter="login"/>

          <el-form>
            <el-form-item style="min-height: 20px; margin-bottom:16px;">
              <div class="text-btn-wrap"
                v-if="loginType === 'pwd'">
                <a class="text-btn"
                  href="javascript:;"
                  @click="changeDialogType('register')">还没账号？<span>立即注册</span></a>
                <a class="text-btn"
                  @click="changeDialogType('forgetPwd')"><span>忘记密码？</span></a>
              </div>
            </el-form-item>

            <el-form-item>
              <el-button class="login-btn"
                :loading="loading"
                type="primary"
                @click="login">登录{{loginType==='phone'?' / 注册':''}}</el-button>
            </el-form-item>

            <el-form-item>
              <div class="checkbox-wrap">
                <el-checkbox v-model="form.isAutoLogin">15天内自动登录</el-checkbox>
                <el-checkbox v-model="form.isRead">
                  <div class="checkbox-btn">已阅读并同意<a @click.prevent="openUrl">用户协议</a></div>
                </el-checkbox>
                <el-checkbox v-model="form.isRemberPwd"
                  v-if="loginType === 'pwd'"
                  class="mt5">记住密码</el-checkbox>
              </div>
            </el-form-item>

          </el-form>

        </div>
      </div>
      <div class="other-login">
        <p class="other-login-title">
          <b></b>
          <span>选择其他登录方式</span>
          <b></b>
        </p>
        <span class="icon-btn" title="快捷登录" v-if="appInfo.isLXAnonymousLogin">
          <svg-icon iconClass="quick"
            class="wechat"
            @click="changeDialogType('anonymousLogin')" />
        </span>
        <span class="icon-btn" title="微信登录">
          <svg-icon iconClass="wechat"
            class="wechat"
            @click="changeDialogType('wxLogin')" />
        </span>
      </div>
    </div>
  </div>
</template>

<script>
import { login } from '@/api/login'
import { debounce, getPwdMD5Str, getTypeOf } from '@/utils'
import { mapGetters } from 'vuex'
import PhoneForm from '@/components/phone-form/index.vue'
import mixins from './mixins'
export default {
  name: 'PhoneLogin',
  mixins: [mixins],
  components: {
    PhoneForm
  },
  props: {
    isPage: Boolean
  },
  data () {
    return {
      loginType: 'phone', // pwd: 手机密码登录 phone: 手机验证码登录 wx: 微信登录 qq: QQ登录
      form: {
        phoneNumber: '',
        code: '',
        codeID: '',
        pwd: '',
        md5Pwd: '', // 选中账号时自动填充的密码【已加密】
        isRemberPwd: false, // 是否记住密码
        isRead: false, // 是否勾选阅读
        isAutoLogin: true // 是否15天内自动登录
      },
      loading: false
    }
  },
  computed: {
    ...mapGetters(['appInfo', 'appCfg']),
    phoneFormLayout () {
      return ['phone2', this.loginType === 'phone' ? 'code' : 'pwd']
    },
    showValidateErrMsg () {
      return (this.$refs.form && this.$refs.form.showValidateErrMsg) || debounce((errMsg) => {
        this.$PsMessage({ message: errMsg, offset: 139 })
      }, 1000, true)
    }
  },
  watch: {
    'form.pwd' () {
      this.form.md5Pwd = ''
    },
    loginType () {
      this.$refs.form.clearValidate()
    }
  },
  created () {
    const phoneAutoLogin = localStorage.getItem('phoneAutoLogin')
    const query = this.$store.state.user.ACDialogQuery
    this.form.isAutoLogin = phoneAutoLogin !== 'false'
    if (query.loginType === 'pwd') {
      this.loginType = 'pwd'
    }
  },
  methods: {
    openUrl () {
      this.$xz('xz_open_url', `${this.appCfg.site}/user-protocol.html`)
    },
    /**
     * 登录
     */
    login () {
      // eslint-disable-next-line sonarjs/cognitive-complexity
      this.$refs.form.validate().then(() => {
        if (!this.form.isRead) {
          return this.showValidateErrMsg('请勾选用户协议')
        }
        const params = {
          'type': this.loginType,
          'phoneNumber': this.form.phoneNumber,
          'codeID': '',
          'code': '',
          'pwd': '',
          'authCode': this.form.phoneNumber, // #test
          'grantType': 'authorization_code', // 授权类型 client_credentials: 客户端凭证 authorization_code:授权码
          'channel': this.appInfo.channel, // 渠道信息
          'uuid': this.appInfo.uuid, // 设备信息
          'device_name': this.appInfo.device_name, // 设备名称
          'version': this.appInfo.version // 版本号
        }
        if (this.loginType === 'phone') {
          params.codeID = this.form.codeID || params.phoneNumber
          params.code = this.form.code
        } else {
          params.pwd = this.form.md5Pwd || getPwdMD5Str(this.form.pwd)
        }
        this.$refs.form.codeError = ''
        this.loading = true
        login(params, { offset: 119 }).then(res => {
          const data = res.data || {}
          data.isAutoLogin = this.form.isAutoLogin
          this.remberAccount(params.phoneNumber, this.form.isRemberPwd ? params.pwd : '')
          localStorage.setItem('phoneAutoLogin', this.form.isAutoLogin)
          if (this.loginType === 'phone') {
            this.$xz('xz_substat_action', 1727)
          } else {
            this.$xz('xz_substat_action', 1731)
          }
          data.loginType = 'phoneLogin'
          this.onLoginFinish(data)
        }).catch(err => {
          if (err) {
            if (err.code === 12001) {
              this.$refs.form.codeError = '验证码错误'
            } else if (err.code === 100429) {
              const data = err.data
              data.isAutoLogin = this.form.isAutoLogin
              data.loginType = 'phoneLogin'
              this.needDelDevice(data)
              this.remberAccount(params.phoneNumber, this.form.isRemberPwd ? params.pwd : '')
            }
          }
        }).finally(e => {
          this.loading = false
        })
      })
    },
    /**
     * 登录成功
     */
    completeLogin (ops) {
      ops.isLogin = true
      this.$store.dispatch('user/setToken', ops.code)
      // this.$store.dispatch('user/getUserInfo', ops)
    },
    /**
     * 记住账号
     * @param {String} phone
     * @param {String|null} pwd
     */
    remberAccount (phone, pwd) {
      let list = localStorage.getItem('phoneAccount')
      try {
        list = JSON.parse(list)
        if (getTypeOf(list) !== 'array') {
          list = []
        }
      } catch (e) {
        list = []
      }
      for (let i = 0; i < list.length; i++) {
        const item = list[i]
        if (item.a === phone) {
          list.splice(i, 1)
          break
        }
      }
      list.splice(2)
      list.unshift({
        a: phone,
        p: pwd
      })
      localStorage.setItem('phoneAccount', JSON.stringify(list))
    },
    /**
     * 切换弹框页面
     * @param {String} type 详见 src/views/login/index.vue comType
     */
    changeDialogType (type) {
      if (type === 'forgetPwd') {
        this.$xz('xz_substat_action', 1729)
      } else if (type === 'wxLogin') {
        this.$xz('xz_substat_action', 1723)
      }
      this.$store.dispatch('user/setACDialogType', type)
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/theme/common/var";
@import "@/styles/other-login.scss";
.body-wrap {
  width: 270px;
}
.head {
  margin-bottom: 20px;
  user-select: none;
  text-align: center;
  span {
    display: inline-block;
    color: #ffffff;
    opacity: 0.7;
    cursor: pointer;
    &:first-child {
      margin-right: 15px;
    }
    &:hover {
      opacity: 1;
    }
    &.active {
      font-size: 16px;
      opacity: 1;
    }
  }
}

.login-btn {
  width: 100%;
}
.checkbox-wrap {
  line-height: 1;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  flex-wrap: wrap;
  min-height: 43px;
  /deep/.el-checkbox {
    margin-right: 0;
  }
  .checkbox-btn {
    a {
      color: $--color-primary;
      display: inline-block;
    }
    &:hover {
      a {
        text-decoration: underline;
      }
    }
  }
}

</style>
